<template>
  <div style="width:100%;">
    <el-row :gutter="10">
      <el-col :span="4">
        <el-button plain type="primary" @click="handleAddDrugOk">
          <template #icon>
            <i-ep-plus/>
          </template>
          添加中药处方模板
        </el-button>
        <el-form ref="formRef" :model="form" :rules="rules">
          <el-table v-adaptive="216" :border="true" :data="form.applyTable" :header-cell-style="$headerCellStyle"
                    :stripe="true" highlight-current-row
                    @row-click="handleAdd">
            <el-table-column :align="'center'" fixed="left" header-align="center" label="序号" prop="rowIndex"
                             width="50">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column fixed="left" label="汤药名" prop="decoctionName">
              <template #default="scope">
                <el-form-item :prop="'applyTable.' + scope.$index + '.decoctionName'"
                              :rules="rules.decoctionName" class="table-form-margin">
                  <el-input v-model="scope.row.decoctionName"
                            clearable></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" class-name="small-padding fixed-width"
                             fixed="right"
                             label="操作" width="80">
              <template #default="scope">
                <el-tooltip class="item" content="模板保存" effect="dark" placement="top">
                  <el-button circle type="success" @click.stop="submitSave(scope.row)">
                    <template #icon>
                      <svg-icon icon-class="save"/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" content="删除" effect="dark" placement="top">
                  <el-button circle type="danger"
                             @click.stop="handleDelete(scope.row)">
                    <template #icon>
                      <i-ep-delete/>
                    </template>
                  </el-button>
                </el-tooltip>
                <!--                <el-tooltip class="item" content="添加药品" effect="dark" placement="top">-->
                <!--                  <el-button circle type="primary"-->
                <!--                             @click="handleAdd(scope.row)">-->
                <!--                    <template #icon>-->
                <!--                      <i-ep-plus/>-->
                <!--                    </template>-->
                <!--                  </el-button>-->
                <!--                </el-tooltip>-->
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>

      <el-col :span="20">
        <el-empty v-if="!currentApplyInfo" description="请先点击左侧处方列表后再添加药品"/>
        <template v-else>
          <el-tooltip class="box-item"
                      content="请先点击左侧处方列表后再添加药品"
                      effect="dark" placement="right">
            <el-button plain type="primary" @click="handleAddDrug">
              <template #icon>
                <i-ep-plus/>
              </template>
              添加药品
            </el-button>
          </el-tooltip>
          <el-form ref="formRef" :model="form" :rules="rules">
            <el-row :gutter="10" class="mt5 top-row">
              <el-form-item class="mr20" label="是否代煎" prop="isDecoction" style="margin-left: 20px">
                <el-select v-model="form.isDecoction" class="width-120"
                           placeholder="请选择">
                  <el-option v-for="dict in decoctionDict" :key="dict.dictValue" :label="dict.dictLabel"
                             :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="mr20" label="途径" prop="channel">
                <administration-index :clearable="false" :placeholder="'请选择途径'"
                                      :value="form.channel" class="width-120"
                                      @administrationInfoChange="administrationInfoChange($event)"/>
              </el-form-item>
              <el-form-item class="mr20" label="频次" prop="performFreq">
                <perform-index ref="performIndex" :clearable="false"
                               :placeholder="'请选择频次'"
                               :value="form.performFreq" class="width-120"
                               @performFreqInfoChange="performFreqInfoChange($event)"/>
              </el-form-item>
              <el-form-item class="mr20" label="剂数" prop="repetition">
                <el-input v-model="form.repetition" clearable style="width: 60px"
                          @blur="repetitionBlur"/>
              </el-form-item>
              <el-form-item class="mr20" label="">
                共计：<span class="mr5" style="color:#ff0000;">{{ itemCount }}</span>味药材，
                总计：<span class="mr5" style="color:#ff0000;">{{ sumMoney }} </span>元
              </el-form-item>
            </el-row>
            <el-row :gutter="10" style="padding-top: 30px;margin-right: 0">
              <el-col v-for="(item, index) in form.detailBoList" :key="index"
                      class="div-style west-style" style="max-width: 15.5%;border-radius: 10px;">
                <div style="margin-bottom: -10px;">{{ index + 1 }}
                  <el-tag key="1" effect="dark" round style="float: right;cursor: pointer;"
                          type="danger" @click="removeDiv(index,item)">
                    X
                  </el-tag>
                  <div class="west-style" style="margin-top: 5px">
                    <el-row :gutter="0">
                      <el-col :span="14">
                        <el-form-item :prop="'detailBoList.' + index + '.itemName'"
                                      :rules="rules.itemName" class="table-form-margin">
                          <el-popover :offset="0" :visible="visibleOpen[index]" placement="bottom"
                                      popper-class="remove-popover" trigger="click" width="1190">
                            <template #reference>
                              <el-input ref="inputRef" v-model="item.itemName"
                                        :tabindex="index" placeholder="请输入需要检索的数据"
                                        @blur="itemNameBlur(index)"
                                        @focus="itemNameInput($event, index, item)"
                                        @input="itemNameInput($event, index, item)"/>
                            </template>
                            <el-table :border="true" :data="tableBodyList" height="200px"
                                      highlight-current-row stripe
                                      @row-click="rowClick($event, index, item)">
                              <el-table-column v-for="(item, index) in tableHeadList" :key="index"
                                               :align="item.align ? item.align : 'center'"
                                               :label="item.label"
                                               :property="item.prop" :show-overflow-tooltip="true"
                                               :width="item.width ? item.width : '90'">
                                <template #default="scope">
                                                    <span v-if="item.class === 'dict'">
                                                        <dict-data-tag :options="dictDataMap[item.dictType]"
                                                                       :value="scope.row[item.prop]"/>
                                                    </span>
                                  <span v-else-if="item.class === 'date'">
                                                        <span>{{
                                                            $parseTime(scope.row[item.prop], '{y}-{m}-{d}')
                                                          }}</span>
                                                    </span>
                                  <span v-else-if="item.class === 'time'">
                                                        <span>{{
                                                            $parseTime(scope.row[item.prop], '{y}-{m}-{d} {h}:{i}:{s}')
                                                          }}</span>
                                                    </span>
                                  <span v-else>
                                                        <span>{{ scope.row[item.prop] }}</span>
                                                    </span>
                                </template>
                              </el-table-column>
                            </el-table>
                            <el-button style="float: right;margin-top: 5px"
                                       @click="closePopover(index)">
                              关闭
                            </el-button>
                          </el-popover>
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item :prop="'detailBoList.' + index + '.num'"
                                      :rules="rules.num"
                                      class="table-form-margin">
                          <el-input v-model="item.num" :class="'num-class' + index"
                                    :tabindex="index + '-' + 1" clearable
                                    placeholder="数量"
                                    @blur="numBlur(index, item)">
                            <template #append>
                              {{ item.unitName }}
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="0">
                      <el-col :span="14">
                        <el-form-item :prop="'detailBoList.' + index + '.remarks'"
                                      class="table-form-margin">
                          <el-input v-model="item.remarks" clearable
                                    placeholder="备注"/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
<!--                        <el-form-item :prop="'v.' + index + '.sumPrice'"-->
<!--                                      class="table-form-margin">-->
<!--                          <el-input v-model="item.sumPrice" disabled>-->
<!--                            <template #append>-->
<!--                              元-->
<!--                            </template>-->
<!--                          </el-input>-->
<!--                        </el-form-item>-->
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {
  delItemIdenticalGroup,
  delTemplateDetail,
  getGroupApplyList,
  insertBoByWholeSet,
  listTemplateDetail
} from "@/api/patient/templateDetail.ts";
import {listSysOrgDict} from "@/api/system/sysOrgDict.ts";
import {autoPrescriptionListByTemplate} from "@/api/drug/drugStock.ts"
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {jsonStrInObj, prescriptionList} from "@/utils/autoComplete.ts";
import {positiveNumberNotNull} from "@/utils/myRules.ts";

const props = defineProps({
  templateMasterId: {
    type: String,
    default: ""
  },
  orgId: {
    type: String,
    default: ""
  },
  deptId: {
    type: String,
    default: ""
  },
})

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no', 'dose_unit', 'sys_drop_speed'))
// 药品总数量
const itemCount = ref(0)
// 药品总金额
const sumMoney = ref(0.00)
//是否代煎字典
const decoctionDict = ref<any>([])
// 选中主记录的当前行
const currentApplyInfo = ref<any>()
const storageId = ref<String>("")
const visibleOpen = ref([false,])
const formRef = ref()
const form = ref<any>({
  applyTable: [],
  detailBoList: [],
  templateMasterId: props.templateMasterId,
})

// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(prescriptionList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

const queryParams = ref<any>({
  type: '1',
  itemClass: "B",
  orgId: props.orgId
});
const itemTable = ref<any>([])

// 主记录表单校验
const rules = ref({
  decoctionName: [
    {required: true, message: "汤药名不能为空", trigger: "blur"}
  ],
  itemName: [
    {required: true, message: "药品名不能为空", trigger: "blur"}
  ],
  isDecoction: [
    {required: true, message: "代煎不能为空", trigger: "change"}
  ],
  channel: [
    {required: true, message: "用药途径不能为空", trigger: "change"}
  ],
  performFreq: [
    {required: true, message: "频次不能为空", trigger: "change"}
  ],
  num: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  repetition: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
})

const autoForm = ref<any>({
  drugClassArray: [],
  storageId: "",
  itemInfo: "",
  orgId: props.orgId
})

/**
 * 处方类别切换事件
 */
function setPrescInfo(drugClass: string, prescAttr: string) {
  autoForm.value.drugClassArray = drugClass.split(",")
  listSysOrgDictFun()
  getList()
}

/**
 * 增加主记录
 */
function handleAddDrugOk() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      form.value.applyTable.push({})
    }
  })
}

/**
 * 增加明细
 */
function handleAdd(row: any) {
  currentApplyInfo.value = row
  if (currentApplyInfo.value.itemIdenticalGroup) {
    getListItem()
  }

}

function getList() {
  getGroupApplyList(queryParams.value).then((response: any) => {
    form.value.applyTable = response.data;
  });
}

/**
 * 查询明细
 */
function getListItem() {
  const param = {
    orgId: props.orgId,
    type: '1',
    itemClass: "B",
    templateMasterId: props.templateMasterId,
    itemIdenticalGroup: currentApplyInfo.value.itemIdenticalGroup,
  }
  form.value.detailBoList = []
  listTemplateDetail(param).then((res: resType) => {
    res.data.forEach((item: any, index) => {
      item.itemId = ""
      item.isShow = true
      item.packageNumCalculate = item.packSize === "1" ? 1 : item.packageNum
      // 设置免皮试 如果是不能编辑状态 noSkin 设置为 true或者false，用于多选按钮选中，否则设置为 Y或者N，用于字典显示
      item.noSkin = item.noSkin === "Y"
      item.singleUnitName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.singleUnit).dictLabel
      const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
      item.unitName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
      form.value.detailBoList.push(item)
      if (index === 0) {
        form.value.channel = item.channel
        form.value.decoctionName = item.decoctionName
        form.value.isDecoction = item.isDecoction
        form.value.itemClass = item.itemClass
        form.value.orgId = item.orgId
        form.value.performFreq = item.performFreq
        form.value.repetition = item.repetition
        form.value.templateMasterId = item.templateMasterId
        form.value.type = item.type
      }
    })
    sunUp()
  })
}


function administrationInfoChange(e: any) {
  const dict = toRaw(e)
  form.value.channel = dict.dictValue
}

/**
 * 频次点击事件
 */
function performFreqInfoChange(e: any) {
  const performFreqInfo = toRaw(e)
  form.value.performFreq = performFreqInfo.freqId
  form.value.performFreqInfo = performFreqInfo
}


/** 剂数焦点消失事件 */
function repetitionBlur() {
  sunUp()
}

function itemNameBlur(index: number) {
  closePopover(index)
}

function closePopover(index: number) {
  visibleOpen.value[index] = false
  // input焦点跳转到num上
  nextTick(() => {
    const nextIndex = index + '-1';
    const nextElement = document.querySelector(`[tabindex="${nextIndex}"]`);
    if (nextElement) {
      //@ts-ignore
      nextElement.focus();
    }
  });
}


/** 计算总金额 */
function sunUp() {
  sumMoney.value = 0.00
  itemCount.value = 0
  let sumMoneyThis = 0.00
  form.value.detailBoList.forEach((item: any) => {
    sumMoneyThis += Number(item.sumPrice)
  })
  sumMoney.value = Number((sumMoneyThis * form.value.repetition).toFixed(4))
  itemCount.value = form.value.detailBoList.length
}

function listSysOrgDictFun() {
  const param = {
    dictType: "clinic_dict",
    delFlag: "0",
    orgId: props.orgId
  }
  listSysOrgDict(param).then((res: resType) => {
    decoctionDict.value = res.data
  })
}


/**
 * 删除单个中药div
 * @param index
 */
function removeDiv(index: number, row: any) {
  ElMessageBox.confirm('删除后数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    if (!row.detailId) {
      form.value.detailBoList.splice(Number(index), 1)
    } else {
      const idsThis = row.detailId
      delTemplateDetail(idsThis).then(() => {
        getListItem()
        ElMessage.success("删除成功")
      })
    }

  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  row.sumPrice = 0.00
  row.singleDosageMin = e.dose
  row.singleDosage = e.dose
  row.singleUnitName = e.doseUnitsName
  row.singleUnit = e.doseUnits
  row.unitName = e.unitsName
  row.minUnits = e.minUnits
  row.packageUnits = e.packageUnits
  row.packageSpec = e.packageSpec
  row.minSpec = e.minSpec
  row.packSize = e.packSize
  row.firmName = e.firmName
  row.firmId = e.firmId
  row.itemName = e.drugName
  row.itemCode = e.drugCode
  row.price = e.price
  row.abidance = 1
  row.sumPrice = e.price * 1
  row.batchNo = e.batchNo
  row.packageNum = e.packageNum
  row.stockId = e.stockId
  row.tradePrice = e.tradePrice
  row.priceId = e.drugPriceId
  row.channel = e.channel
  row.performFreq = e.performFreq
  row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
  row.drugInfoId = e.drugInfoId
  row.identicalInfoId = e.identicalInfoId
  row.sort = index + 1
  tableBodyList.value = []
  // closePopover(index)
}

/** 项目名称自动补全检索 */
function itemNameInput(itemName: String, index: number, item: any) {
  if (typeof itemName == "string") {
    autoForm.value.itemInfo = itemName
  } else {
    autoForm.value.itemInfo = item.itemName
  }
  getListDrugItem(index)
}

/** 自动补全后台查询 */
function getListDrugItem(index: number) {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = props.orgId
    // 打开自动补全弹出框
    visibleOpen.value[index] = true
    autoPrescriptionListByTemplate(autoForm.value).then(res => {
      tableBodyList.value = res.data
    })
  } else {
    tableBodyList.value = []
  }
}

/** 添加药品 */
function handleAddDrug() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      form.value.detailBoList.push({
        // 是否免皮试 保存、修改时需要单独处理 true-> Y , false-> N
        noSkin: true,
        sumPrice: 0.00,
        price: 0.00,
        itemName: "",
        abidance: 1,
        num: 1
      })
      visibleOpen.value.push(false)
    }
  })
}

/**
 * 模板保存
 */
function submitSave(row: any) {
  (formRef.value as any).validate(valid => {
    if (valid) {
      ElMessageBox.confirm('确定要进行保存操作吗？',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        form.value.itemClass = "B"
        form.value.type = "1"
        form.value.orgId = props.orgId
        form.value.templateMasterId = props.templateMasterId
        form.value.decoctionName = row.decoctionName
        form.value.detailBoList.forEach((item: any) => {
          item.noSkin = "Y"
          item.isSkin = "N"
        })
        insertBoByWholeSet(form.value).then(() => {
          ElMessage.success("药品明细保存成功")
          getList()
        })
      })
    }
  })
}

/**
 * 删除主记录
 */
function handleDelete(row: any) {
  const param = {
    itemIdenticalGroup: row.itemIdenticalGroup,
    templateMasterId: row.templateMasterId,
    detailId: row.detailId
  };
  ElMessageBox.confirm("是否确认删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delItemIdenticalGroup(param).then(() => {
        ElMessage.success("删除成功");
        getList();
        form.value.detailBoList = []
        currentApplyInfo.value = {}
      });
    })
    .catch(() => {
    });
}

/**
 * 数量input焦点消失事件
 * @param e
 * @param index
 * @param item
 */
function numBlur(_index: number, item: any) {
  item.sumPrice = Number((item.price * item.num).toFixed(4))
  sunUp()
}


defineExpose({
  handleAddDrugOk,
  setPrescInfo,
  getList
})
</script>

<style scoped>
.west-style {
  margin: 10px 10px 10px 7px;
  padding: 0;
  background-color: #c6f4ce;
}

:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 70px;
}

.top-row {
  background-color: #68e3fd;
  margin-left: 1px !important;
  height: 27px;
  position: absolute;
  z-index: 1;
  width: 100%;
}
</style>
